<?php

namespace app\common\util;

use app\common\model\trResource;

/**
 * Class UeditorController
 * @package Admin\Controller
 */
class Uploads
{
    public $savePath = 'image/';
    public $root;
    public $rootUrl;

    public function __construct()
    {
        header("Content-Type: text/html; charset=utf-8");
        $this->root = config('upload.basePath') . request()->mallData["id"] . "/";
        $this->rootUrl = "/" . config('upload.uploadBase') . request()->mallData["id"] . "/";
    }

    public function ueditor($userId = 0)
    {
        $CONFIG2 = config('upload.ueditor');
        $action = input('action', '', 'htmlspecialchars');
        $result = '';
        switch ($action) {
            case 'config':
                $result = $CONFIG2;
                break;
            /* 上传图片 */
            case 'uploadimage':
                $config = array(
                    "ext" => $CONFIG2['imageAllowFilesTP'],
                    "size" => $CONFIG2['imageMaxSize'],
                );
                $fieldName = $CONFIG2['imageFieldName'];
                $result = $this->upImage($fieldName, $config, $userId);
                break;
            /* 列出图片 */
            case 'listimage':
                $listSize = $CONFIG2['imageManagerListSize'];
                $get = $_GET;
                $result = $this->fileLists($listSize, $get);
                break;
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $CONFIG2['fileManagerAllowFiles'];
                $listSize = $CONFIG2['fileManagerListSize'];
			    $path = '/' . config('uploadBase') . $this->savePath . "file/";
                $get = $_GET;
                $result = $this->fileList($path, $allowFiles, $listSize, $get);
                break;
        }
        return $result;
    }

    //上传图片
    public function upImage($fieldName, $validate, $userId)
    {
        $file = request()->file($fieldName);
        if (empty($file)) {
            $file = json_decode(request()->param($fieldName), true);
        }
        if (empty($file)) {
            return array('msg' => "文件不存在");
        } else {
            $dir = $this->savePath . date('Y-m') . '/' . date('d') . '/';
            $newFile = md5(time()).".".pathinfo($file["name"], PATHINFO_EXTENSION);
            Tools::mkdir(request()->server("DOCUMENT_ROOT")."/".$this->root . $dir);
            file_put_contents(request()->server("DOCUMENT_ROOT")."/".$this->root . $dir . $newFile, base64_decode($file["content"])); // 把文件流写入临时文件
            $data = array(
                'url' => $this->rootUrl . $dir . $newFile,
                'title' => pathinfo($newFile, PATHINFO_BASENAME ),
                'type' => '.' . pathinfo($newFile, PATHINFO_EXTENSION ),
                'size' => $file["size"],
                'state' => "SUCCESS"
            );
            $data["id"] = explode('.', $data['title'])[0];
            //存储图片到数据库
            trResource::add(array(
                'id' => $data["id"],
                'name' => $data['title'],
                'location' => explode('/', request()->path())[0],
                'url' => $data['url'],
                "user_id" => $userId,
                'time' => time()
            ));
            $data['url'] = tome_dia($data['url']);
        }
        return $data;
    }

    //上传图片
//    public function upImage_bak($fieldName, $validate, $userId)
//    {
//        $file = request()->file($fieldName);
//        if (empty($file)) {
//            $file = request()->file('upfile');
//        }
//        if (empty($file)) {
//            return array('msg' => "文件不存在");
//        } else {
//            // 移动到框架应用根目录/public/attachment/ 目录下
//            $this->savePath = $this->savePath . date('Y-m') . '/' . date('d') . '/';
//            // 使用自定义的文件保存规则
//            $info = $file->validate($validate)->rule(function ($file) {
//                return md5(time());
//            })->move($this->root . $this->savePath);
//        }
//
//        if ($info) {
//            $data = array(
//                'url' => $this->rootUrl . $this->savePath . $info->getSaveName(),
//                'title' => $info->getFilename(),
//                'type' => '.' . $info->getExtension(),
//                'size' => $info->getSize(),
//                'state' => "SUCCESS"
//            );
//            $data["id"] = explode('.', $data['title'])[0];
//            //存储图片到数据库
//            trResource::add(array(
//                'id' => $data["id"],
//                'name' => $data['title'],
//                'location' => explode('/', request()->path())[0],
//                'url' => $data['url'],
//                "user_id" => $userId,
//                'time' => time()
//            ));
//            $data['url'] = tome_dia($data['url']);
//        } else {
//            return array('msg' => $file->getError());
//        }
//        return $data;
//    }

    /**
     * @param $fieldName
     * @param $validate
     * @param int $userId
     * @param string $extra
     * @return array
     * 文件上传
     */
    public function upFile($fieldName, $validate, $userId = 0, $extra = '')
    {
        // 获取表单上传文件
        $file = request()->file($fieldName);
        if (empty($file)) {
            $file = request()->file('file');
        }

        if(!is_null($file)) {
            $original = $file->getInfo('name');
            $fileInfo = pathinfo($original);

            // 使用自定义的文件保存规则
            $info = $file->validate($validate)->rule(function () use ($fileInfo) {
                return mt_rand();
            })->move($this->root . $this->savePath);
            if ($info) {
                $state = "SUCCESS";
                $data = array(
                    'state' => $state,
                    'url' => $this->rootUrl . $this->savePath . $info->getSaveName(),
                    'title' => $info->getFilename(),
                    'original' => $info->getFilename(),
                    'msg' => "上传成功"
                );
                if(empty($extra)){
                    $data["id"] = explode('.', $data['title'])[0];
                    trResource::add(array(
                        'id' => $data["id"],
                        'name' => $data['title'],
                        'location' => explode('/', request()->path())[0],
                        'type' => 2,
                        'url' => $data['url'],
                        "user_id" => $userId,
                        'time' => time()
                    ));
                    $data['url'] = tome_dia($data['url']);
                }else { //源码上传
                    trResource::add(array(
                        'id' => $extra,
                        'name' => $data['title'],
                        'location' => explode('/', request()->path())[0],
                        'type' => 3,
                        'url' => $data['url'],
                        "user_id" => $userId,
                        'time' => time()
                    ));
                    $data['id'] = $data['url'];
                    $data['url'] = tome_dia($data['url']);
                }
            } else {
                $data = array(
                    'state' => 'ERROR',
                    'msg' => $file->getError(),
                );
            }
        }else{
            $data = array(
                'state' => 'ERROR',
                'msg' => '上传出错了，请检查下PHP配置',
            );
        }
        return $data;
    }

    /**
     * 数据库列出图片
     */
    public function fileLists($listSize, $get){

        /* 获取参数 */
        $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
        $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;

        /* 获取文件列表 */
        $file = trResource::where('type', 'admin')->order('time', 'desc')
            ->field('url,time')
            ->paginate(array('list_rows'=>$size,'page'=>$start/$size));
        $data = $file->items();
        if (!count($data)) {
            return json_encode(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => $file->total()
            ));
        }
        $list = [];
        foreach ($data as $item){
            $list[] = ['url' => request()->domain() . __PUBLIC__ . $item['url'],'mtime' => $item['time']];
        }

        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => $file->total()
        ));

        return $result;
    }

    //列出图片
    public function fileList($path, $allowFiles, $listSize, $get)
    {
        $path = '.' . $path;
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
        /* 获取参数 */
        $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
        $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;
        $end = $start + $size;
        /* 获取文件列表 */
        $files = $this->getFiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }
        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }

        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));

        return $result;
    }

    /*
  * 遍历获取目录下的指定类型的文件
  * @param $path
  * @param array $files
  * @return array
 */
    public function getFiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);

        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getFiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = array(
                            'url' => substr($path2, 1),
                            'mtime' => filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }
}